import React, { useEffect, useState } from 'react'
import { Button, Cascader, DatePicker, Drawer, Form, Input, message, Select, Spin } from 'antd'
import type { DictItem, optionConfigType, orderType } from '@/types'
import useChinaAreasStore from '@/store/chinaAreas'
import http from '@/utils/request'
import './index.scss'
import dayjs from 'dayjs'

const orderAdd: React.FC<{
  isOpen: boolean,
  onClose: (refresh?: boolean) => void,
  optionConfig: optionConfigType,
  typeDict: DictItem[],
  order?: orderType
}> = ({ isOpen, onClose, optionConfig, typeDict, order }) => {

  const [addForm] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [orderTypeVal, setOrderTypeVal] = useState<string>('')
  const { chinaAreas } = useChinaAreasStore()
  const { fetchChinaAreas } = useChinaAreasStore()

  const initVal: { [key: string]: any } = {
    addressCodes: order?.areaCode ? [order?.provinceCode, order?.cityCode, order?.areaCode] as number[] : []
  }
  useEffect(() => {
    const keys = ['orderType',
      'customerPhone',
      'customerName',
      'bizTypeId',
      'comboId',
      'giftId',
      'processingDetail',
      'customerAddress',
      'provinceCode',
      'cityCode',
      'areaCode']
    const dateKeys: string[] = ['appointmentProcessingDate', 'intendedDate']
    if (isOpen && order) {
      keys.forEach(key => {
        initVal[key] = order[key as keyof orderType] || undefined
      })
      dateKeys.forEach(item => {
        const key = item as keyof orderType
        initVal[key] = order[key as keyof orderType] ? dayjs(order[key] as string) : undefined
      })
    }
    isOpen && addForm.resetFields()
    fetchChinaAreas()
  }, [isOpen])

  const handleCancel = () => {
    onClose()
  }
  const handleOk = () => {
    addForm?.validateFields().then(values => {
      console.log(values)
      const params = Object.keys(values).reduce((obj: {[key: string]: any}, key) => {
        if (['appointmentProcessingDate', 'intendedDate'].includes(key)) {
          obj[key] = values[key] && values[key].format('YYYY-MM-DD HH:mm:ss')
        } else if ('addressCodes' === key) {
          obj.provinceCode = values[key]?.[0]
          obj.cityCode = values[key]?.[1]
          obj.areaCode = values[key]?.[2]
        } else {
          obj[key] = values[key]
        }
        return obj
      }, {})
      let url = '/disp/biz/order/insert'
      if (order && order.id) {
        params.id = order.id
        url = '/disp/biz/order/updateOrder'
      }
      setLoading(true)
      http.post(url, params).then(() => {
        message.success(params.id ? '编辑成功' : '添加成功')
        onClose(true)
      }).catch(err => {
        message.error(err.msg || '创建订单失败')
      }).finally(() => {
        setLoading(false)
      })
    }).catch(err => {
      console.log(err)
    })
  }
  // const addressChange = (selected: CascaderOption[]) => {
  //   addForm.setFieldsValue({
  
  //   })
  // }
  const handTypeChange = (val: string) => {
    setOrderTypeVal(val)
    addForm.validateFields(['appointmentProcessingDate'])
  }
  const checkPhoneNumberExists = (value: any) => {
    return http.post('/disp/biz/order/queryExistNum', {
      customerPhone: value
    })
  }

  const filter = (inputValue: string, path: any[]) =>
    path.some(
      (option) => (option.name as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    )

  return (<Drawer
    title={order ? '编辑订单' : '新增订单'}
    width={600}
    onClose={() => onClose(false)}
    open={isOpen}
    footer={
      <div className="button-container flex-row">
        <div className="flex1"/>
        <Button onClick={handleCancel} className="btn">取 消</Button>
        <Button onClick={handleOk} loading={loading} className="btn" type="primary">保 存</Button>
      </div>
    }>
    <Spin spinning={loading}>
      <div className="drawer-container flex-column">
        <Form
          form={addForm}
          initialValues={initVal}
          style={{ marginTop: 20 }}
          layout="vertical">
          {!order ? <Form.Item<orderType>
            label="订单类型"
            name="orderType"
            rules={[{ required: true, message: '请选择订单类型' }]}
          >
            <Select
              style={{ width: '100%' }}
              placeholder="请选择订单类型"
              onChange={handTypeChange}
              options={typeDict}
              allowClear/>
          </Form.Item> : null}

          <Form.Item<orderType>
            label="客户手机"
            name="customerPhone"
            rules={[
              { required: true, message: '请输入客户手机号' },
              {
                validator: async (_, value) => {
                  // 2. 校验手机号格式
                  if (!/^1[3-9]\d{9}$/.test(value)) {
                    throw new Error('请输入合法的11位手机号码')
                  }
                  let isExist
                  try {
                    setLoading(true)
                    isExist = await checkPhoneNumberExists(value)
                  } finally {
                    setLoading(false)// 调用 API 检查手机号
                  }
                  if (isExist?.data?.existNum !== 0 && !(order?.id)) {
                    return Promise.reject(new Error('系统中已存在该号码'))
                  }
                },
                warningOnly: true
              }
            ]}
          >
            <Input
              allowClear
              placeholder="请输入"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item<orderType>
            label="客户姓名"
            name="customerName"
            rules={[{ required: true, message: '请输入客户姓名' }]}
          >
            <Input
              allowClear
              placeholder="请输入"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item<orderType>
            label="业务类型"
            name="bizTypeId"
            rules={[{ required: false, message: '请选择业务类型' }]}
          >
            <Select
              allowClear
              placeholder="请选择"
              style={{ width: '100%' }}
              options={optionConfig.bizTypes}
            />
          </Form.Item>

          <Form.Item<orderType>
            label="套餐"
            name="comboId"
            rules={[{ required: false, message: '请选择套餐' }]}
          >
            <Select
              allowClear
              placeholder="请选择"
              style={{ width: '100%' }}
              options={optionConfig.comboIds}
            />
          </Form.Item>

          {/* { order && order.fullAddressName ? <div className="old-address"> */}
          {/*   原地址： {order.fullAddressName} */}
          {/* </div> : null } */}

          <Form.Item name="provinceCode" noStyle rules={[]}>
            <Input type="hidden" />
          </Form.Item>
          <Form.Item name="cityCode" noStyle rules={[]}>
            <Input type="hidden" />
          </Form.Item>
          <Form.Item name="areaCode" noStyle rules={[]}>
            <Input type="hidden" />
          </Form.Item>

          <Form.Item<orderType>
            label={order && order.customerAddress ? '修改地址' : '客户地址'}
            name="addressCodes"
            rules={[{ required: !order?.belongingArea, message: '请输入地址' }]}
          >
            <Cascader
              options={chinaAreas}
              fieldNames={{
                label: 'name',
                value: 'region',
                children: 'childRegion'
              }}
              placeholder="请选择省市区"
              changeOnSelect
              showSearch={{ filter }}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item<orderType>
            label="详细地址"
            name="customerAddress"
            rules={[{ required: false }]}
          >
            <Input
              allowClear
              placeholder="请输入详细地址"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item<orderType>
            label="礼品"
            name="giftId"
            rules={[{ required: false }]}
          >
            <Select
              allowClear
              placeholder="请选择"
              style={{ width: '100%' }}
              options={optionConfig.gifts}
            />
          </Form.Item>
          <Form.Item<orderType>
            label="可办理日期"
            name="appointmentProcessingDate"
            rules={[{ required: orderTypeVal === 'Intentional', message: '可办理日期' }]}
          >
            <DatePicker
              style={{ width: '100%' }}
              disabledDate={(current) => {
                return current && current < dayjs().startOf('day')
              }}
              placeholder="请选择日期"
              allowClear/>
          </Form.Item>

          <Form.Item<orderType>
            label="办理详情"
            name="processingDetail"
            rules={[{ required: false }]}
          >
            <Input
              allowClear
              placeholder="请输入"
              style={{ width: '100%' }}
            />
          </Form.Item>
          {
            orderTypeVal === 'Intentional' ?
              <Form.Item<orderType>
                label="意向日期"
                name="intendedDate"
                rules={[{ required: true, message: '请选择团队' }]}
              >
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="请选择日期"
                  allowClear/>
              </Form.Item> : null
          }
        </Form>
      </div>
    </Spin>
  </Drawer>)
}

export default orderAdd
